<template>
  <!-- TODO: 配置草稿箱状态管理+持久化 -->
  <div class="editor-container">
    <v-container fluid>
      <v-row>
        <v-col cols="4">
          <div class="cover">
            <v-img aspect-ratio="16/9" cover :src="coverImg" :width="200" />
            <v-file-input width="200px" label="Cover Image Upload" prepend-icon="mdi-camera" show-size
              accept="image/png, image/jpeg, image/bmp" placeholder="Upload your cover" variant="underlined"
              @change="handleCover" />
          </div>
        </v-col>
        <v-col cols="4">
          <div class="title">
            <v-text-field max-width="400px" hide-details="auto" label="Main input"></v-text-field>
          </div>
        </v-col>
        <v-col cols="4">
          <div class="tags">
            <v-select v-model="selectTags" clearable chips label="Select"
              :items="['JS', 'Vue', 'React', 'Angular', 'Node', 'Python']" multiple variant="outlined"></v-select>
          </div>
        </v-col>
      </v-row>
      <v-row>
        <v-col cols="12">
          <div class="md-editor">
            <MdEditor style="height: 900px;" ref="mdEditorRef" v-model="text" :toolbars="toolbars" @on-save="onSave"
              @on-upload-img="onUploadImg" />
          </div>
        </v-col>
      </v-row>
      <v-row>
        <v-col cols="12">
          <div class="btn">
            <v-btn :disabled="!isAllowedSumit || loading" prepend-icon="mdi-check" color="success" block
              @click="onSubmit">
              <v-icon v-if="loading" icon="mdi-spin mdi-loading"></v-icon>
              {{ loading ? '提交中...' : '提交文章' }}
            </v-btn>
          </div>
        </v-col>
      </v-row>
      <!-- 状态提示 -->
      <div class="status-alert-container">
        <v-alert 
          v-if="successMessage" 
          type="success" 
          variant="tonal" 
          class="status-alert"
        >
          {{ successMessage }}
        </v-alert>

        <v-alert 
          v-if="errorMessage" 
          type="error" 
          variant="tonal" 
          class="status-alert"
        >
          {{ errorMessage }}
        </v-alert>
      </div>
    </v-container>
  </div>
</template>

<route lang="json">{
  "name": "editor",
  "meta": {
    "title": "editor"
  }
}</route>

<script setup lang="ts">
// 引入组件
import { MdEditor, type ToolbarNames } from 'md-editor-v3'
import { uploadArticle, uploadArticleImg } from '@/apis/comp'
import { useMarkdownStore } from '@/stores/md'
import { ref, computed } from 'vue'

// 状态管理
const selectTags = ref<string[]>([])
const loading = ref(false)
const successMessage = ref('')
const errorMessage = ref('')

// 定义工具栏显示项
const toolbars = [
  'bold',
  'underline',
  'italic',
  '-',
  'title',
  'strikeThrough',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  'task',
  '-',
  'codeRow',
  'code',
  'link',
  'image',
  'table',
  'mermaid',
  'katex',
  '-',
  'revoke',
  'next',
  'save',
  '=',
  'preview',
  'htmlPreview',
  'catalog',
  'github',
] as ToolbarNames[]

const mdStore = useMarkdownStore()
const text = ref(mdStore.getMD() || '## 你好，Markdown编辑器！') // 初始内容

// 提交验证
const isAllowedSumit = computed(() => text.value.trim() !== '' && coverImg.value !== defaultCover && coverImg.value !== '' && selectTags.value.length > 0)
// 显示提示信息的通用函数
function showMessage(type: 'success' | 'error', message: string, duration: number = 3000) {
  if (type === 'success') {
    successMessage.value = message
    errorMessage.value = ''
  } else {
    errorMessage.value = message
    successMessage.value = ''
  }

  // 定时清除提示
  setTimeout(() => {
    if (type === 'success') {
      successMessage.value = ''
    } else {
      errorMessage.value = ''
    }
  }, duration)
}

// 图片上传处理函数
async function onUploadImg(files: File[], callback: (urls: string[]) => void) {
  // 这里实现你的图片上传逻辑，例如调用后端接口
  const urls: string[] = []
  loading.value = true
  try {
    for (const file of files) {
      // 模拟上传成功，返回图片URL
      // 在实际应用中，你需要替换为真实的上传接口调用
      const url = await upload(file)
      urls.push(url)
    }
    callback(urls) // 将图片URL数组回传给编辑器
    showMessage('success', '图片上传成功！')
  } catch (error) {
    showMessage('error', '图片上传失败，请重试')
    console.error('图片上传错误:', error)
  } finally {
    loading.value = false
  }
}

async function upload(file: File) {
  const formdata = new FormData()
  formdata.append('article', file)
  console.log(formdata)
  try {
    const res = await uploadArticleImg(formdata)
    console.log(res)
    return res.url
  } catch (error) {
    console.error('上传失败:', error)
    throw error
  }
}

// 上传封面图片
const defaultCover = 'https://cdn.vuetifyjs.com/images/parallax/material.jpg'
const coverImg = ref(mdStore.getCover() || defaultCover)
async function handleCover(event: Event) {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return

  loading.value = true
  try {
    const url = await upload(file as File)
    coverImg.value = url
    mdStore.setCover(url)
    showMessage('success', '封面图片上传成功！')
  } catch (error) {
    showMessage('error', '封面图片上传失败，请重试')
    console.error('封面上传错误:', error)
  } finally {
    loading.value = false
  }
}

const mdEditorRef = ref(null)
// 保存： 保存到本地，状态
function onSave(value: string) {
  // console.log('保存:', value)
  mdStore.setMD(value)
  // 保存其他状态
  showMessage('success', '内容已保存！', 2000)
}

// 提交
async function onSubmit() {
  if (!isAllowedSumit.value) return

  loading.value = true
  try {
    const articleObj: any = {
      content: text.value,
      cover: coverImg.value,
      tags: selectTags.value,
    }
    await uploadArticle(articleObj)
    showMessage('success', '文章提交成功！')

    // 状态清理
    // 可以选择是否重置表单
    // text.value = ''
    // coverImg.value = defaultCover
    // selectTags.value = []
  } catch (error) {
    showMessage('error', '文章提交失败，请重试')
    console.error('文章提交错误:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="less">
.editor-container {
  width: 100%;

  .md-editor {
    height: 100%;
    padding: 16px;
    border: 1px solid #000;
  }

  .cover {
    width: 50%;
    height: auto;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .title {
    margin-top: 50px;
  }

  .tags {
    margin-top: 50px;
  }

  .btn {
    border: 1px solid #000;
    width: 400px;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  /* 状态提示样式 */
  .status-alert-container {
    position: fixed;
    top: 10%;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    max-width: 500px;
    pointer-events: none;
  }
  
  .status-alert {
    width: 100%;
    margin: 8px 0;
    animation: slideDown 0.3s ease-out forwards, fadeOut 0.3s ease-in forwards 2.7s;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    pointer-events: auto;
  }
  
  @keyframes slideDown {
    from {
      opacity: 0;
      transform: translateY(-50px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  @keyframes fadeOut {
    from {
      opacity: 1;
      transform: translateY(0);
    }
    to {
      opacity: 0;
      transform: translateY(-20px);
    }
  }
}
</style>
